/*

Copyright (C) 2010  Christoph Schnack 

    This file is part of Tribuit.

    Tribuit is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Tribuit is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tribuit.  If not, see <http://www.gnu.org/licenses/>.
*/

package VMAddManyWords;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

import GuiTools.*;
import Mainframe.Mainframe;
import Settings.*;
import Storage.*;
import VocabularyManagement.EditVocDialog;

public class AddManyWords{
	private TribuitFrame amwFrame;
	private JComboBox stTermclassACB,stTermclassBCB;
	private Vocabulary vocToAdd;
	private JPanel centerPanel;
	private GridBagConstraints gbc;
	private Vector <WordRowAdvanced> rows = new Vector <WordRowAdvanced>();
	private JSpinner count;
	private int rowNumber=10;
	private SectionChooser sectionChooser;
	private Storage MAINVOC;
	private Settings SET;
	private Language LANG;
	private Mainframe MAINFRAME;
	private MDManager VMDM;
	private boolean RETURNTOPREVIOUSDIALOG=true;
	
	public AddManyWords(String voc,Storage mainvoc, Settings set,Mainframe mf,MDManager vmdm){
		MAINVOC = mainvoc;
		SET = set;
		LANG = SET.getLanguage();
		MAINFRAME=mf;
		VMDM = vmdm;
		vocToAdd=MAINVOC.getVocabulary(voc);
		buildGui();
	}
	
	public AddManyWords(String voc,Storage mainvoc, Settings set, Mainframe mf){
		MAINVOC = mainvoc;
		SET = set;
		MAINFRAME=mf;
		LANG = SET.getLanguage();
		vocToAdd=MAINVOC.getVocabulary(voc);
		RETURNTOPREVIOUSDIALOG=false;
		buildGui();
	}
	
	private void buildGui(){
		gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.CENTER;
		gbc.insets = new Insets(30,10,0,10);
		if(RETURNTOPREVIOUSDIALOG)amwFrame = new MDTribuitFrame(LANG.getAddVariousWords(),VMDM);
		else amwFrame=new TribuitFrame (LANG.getAddVariousWords());
		stTermclassACB = new JComboBox(vocToAdd.getSortedTermClassKeysA());
		stTermclassACB.setPreferredSize(new Dimension(120,26));
		stTermclassBCB = new JComboBox(vocToAdd.getSortedTermClassKeysB());
		stTermclassBCB.setPreferredSize(new Dimension(120,26));
		stTermclassACB.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				setRowPanels(true);
				amwFrame.packAndKeepBounds();
				amwFrame.repaint();
			}
		});
		stTermclassBCB.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				setRowPanels(true);
				amwFrame.packAndKeepBounds();
				amwFrame.repaint();
			}
		});
		
		SpinnerModel model = new SpinnerNumberModel(rowNumber,1,100,1); 
		count = new JSpinner(model);
		count.addChangeListener(new ChangeListener(){
			public void stateChanged(ChangeEvent arg0) {
				rowNumber=(Integer)count.getValue();
				setRowPanels(false);
				amwFrame.packAndKeepBounds();
				amwFrame.repaint();
			}
		});
		sectionChooser = new SectionChooser(SET,vocToAdd.getLections());
		
		JPanel defaultTCPanel = new JPanel();
		defaultTCPanel.setLayout(new BoxLayout(defaultTCPanel,BoxLayout.Y_AXIS));
		defaultTCPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black),LANG.getTermClass()));
		defaultTCPanel.add(new LabelPanel(vocToAdd.getNameA()+":",stTermclassACB));
		defaultTCPanel.add(new LabelPanel(vocToAdd.getNameB()+":",stTermclassBCB));
		
		JPanel defaultSectionPanel = new JPanel();
		defaultSectionPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black),LANG.getSection()));
		defaultSectionPanel.add(sectionChooser);

		JLabel settingsLabel = new JLabel(LANG.getSettings());
		settingsLabel.setHorizontalAlignment(JLabel.CENTER);
		settingsLabel.setForeground(Color.white);
		settingsLabel.setFont(new Font(Font.SANS_SERIF,Font.BOLD,20));
		
		JPanel settingsPanel = new JPanel();
		settingsPanel.setLayout(new GridBagLayout());
		GridBagConstraints spGbc = new GridBagConstraints();
		spGbc.anchor = GridBagConstraints.NORTHWEST;
		spGbc.gridx = GridBagConstraints.REMAINDER;
		spGbc.fill = GridBagConstraints.HORIZONTAL;
		spGbc.insets = new Insets(0,5,10,5);
		settingsPanel.add(defaultTCPanel,spGbc);
		settingsPanel.add(defaultSectionPanel,spGbc);
		
		settingsPanel.setBorder(BorderFactory.createTitledBorder(LANG.getDefaults()+":"));
		
		JPanel counterPanel = new JPanel();
		counterPanel.setBorder(BorderFactory.createTitledBorder(LANG.getFormularCount()+":"));
		counterPanel.add(count);
		
		JPanel fillPanel = new JPanel();
		fillPanel.setOpaque(false);
		
		JPanel westPanel = new JPanel(new GridBagLayout());
		spGbc.insets = new Insets(10,5,10,5);
		westPanel.add(settingsLabel,spGbc);
		westPanel.add(settingsPanel,spGbc);
		westPanel.add(counterPanel,spGbc);
		spGbc.fill = GridBagConstraints.HORIZONTAL;
		spGbc.weighty = 1;
		westPanel.add(fillPanel,spGbc);
		westPanel.setBackground(Color.gray);
		
		JPanel buttonPanel = new JPanel();
		JButton cancelBtn = new JButton(LANG.getCancel());
		cancelBtn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				amwFrame.dispose();
				if(RETURNTOPREVIOUSDIALOG)new EditVocDialog(MAINVOC,SET,MAINFRAME,VMDM);
			}
		});
		JButton okBtn = new JButton(LANG.getOdConfirm());
		okBtn.addActionListener(new OkBtnListener());
		buttonPanel.add(okBtn);
		buttonPanel.add(cancelBtn);
		buttonPanel.setBackground(GuiTools.BGCOLOR);
		
		centerPanel = new JPanel();
		//centerPanel.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
		centerPanel.setLayout(new GridBagLayout());
		centerPanel.setBackground(Color.darkGray);
		setRowPanels(false);
		CustomScrollPane jsp = new CustomScrollPane(centerPanel,50,50);
		jsp.setPreferredSize(new Dimension(900,400));
		
		JPanel mainPanel = new JPanel(new BorderLayout());
		mainPanel.add(BorderLayout.WEST,westPanel);
		mainPanel.add(BorderLayout.CENTER, jsp);
		
		amwFrame.getContentPane().add(BorderLayout.NORTH,new Header(LANG.getAddVariousWords()));
		amwFrame.getContentPane().add(BorderLayout.CENTER, mainPanel);
		amwFrame.getContentPane().add(BorderLayout.SOUTH, buttonPanel);
		amwFrame.setResizable(true);
		amwFrame.showUp(50,100);
		amwFrame.addWindowListener(new WindowAdapter() {
		      public void windowClosing(WindowEvent e){
		    	  if(RETURNTOPREVIOUSDIALOG)new EditVocDialog(MAINVOC,SET,MAINFRAME,VMDM);
		        }
		      });
		rows.elementAt(0).grabFocusFirstElement();
	}
	
	private void setRowPanels(boolean termclassEvent){
		centerPanel.removeAll();
		if(rowNumber>rows.size()){
			while(rows.size()<rowNumber){
				rows.add(new WordRowAdvanced(amwFrame,this,SET,vocToAdd,rows.size()+1));
			}
		}
		else{
			while(rows.size()>rowNumber){
				rows.removeElementAt(rows.size()-1);
			}
		}
		for(int i=0;i<rowNumber;i++){
			gbc.gridy = i;
			centerPanel.add(rows.elementAt(i),gbc);
			if(termclassEvent){
				rows.elementAt(i).setTermClassA((String)stTermclassACB.getSelectedItem());
				rows.elementAt(i).setTermClassB((String)stTermclassBCB.getSelectedItem());
			}
		}
	}
	
	public String getStandardSection(){
		return sectionChooser.getSectionSelection();
	}
	
	private Vector<Word> generateWordsToAdd(){
		Vector<Word> result = new Vector<Word>();
		Word w;
		boolean duplicate = false;
		for(WordRowAdvanced wr : rows){
			wr.resetErrors();
			duplicate = false;
			if(!wr.isInaccurate()){
				w = new Word(wr.getSection(),wr.getTermClassA(),wr.getTermClassB(),wr.getMeaningsA(),wr.getMeaningsB());
				for(Word wrd : result){
					if(w.getName().equals(wrd.getName())){
						wr.setErrorAB(LANG.getDuplicateEntry());
						duplicate = true;
						break;
					}
				}
				if(!duplicate){
					if(!vocToAdd.hasWord(w.getName())){
						result.add(w);
						wr.resetAllInputs();
					}
					else wr.setErrorAB(LANG.getWordAlreadyExists());
				}
			}
		}
		amwFrame.pack();
		amwFrame.repaint();
		return result;
	}
	
	private class OkBtnListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			Vector<Word> wta = generateWordsToAdd();
			if(wta.size()==0){
				JOptionPane.showMessageDialog(amwFrame, LANG.getErrorDuringCreatingNewWords()+": "+LANG.getInvalidInput(), LANG.getAttention(), JOptionPane.ERROR_MESSAGE);
				return;
			}
			amwFrame.setVisible(false);
			String vocName = vocToAdd.getName();
			JPanel adds = new JPanel();
			adds.setLayout(new BoxLayout(adds,BoxLayout.Y_AXIS));
			boolean oldAutosave = SET.getAutosave();
			SET.setAutosave(false);
			StringBuffer sb = new StringBuffer();
			sb.append("<HTML><BODY>");
			int addedWordsCounter = 0;
			for(int i=0;i<wta.size();i++){
				if(!vocToAdd.hasWord(wta.elementAt(i).getName())){
					MAINVOC.addWordToVoc(vocName,wta.elementAt(i));
					sb.append(wta.elementAt(i).getName()+"<br>");
					addedWordsCounter++;
				}
			}
			sb.append("</BODY></HTML>");
			JLabel info = new JLabel(addedWordsCounter+" "+LANG.getWords()+" "+LANG.getAdded()+":");
			info.setFont(new Font(Font.SANS_SERIF,Font.BOLD,15));
			adds.add(info);
			JLabel label = new JLabel(sb.toString());
			label.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,15));
			adds.add(label);
			MAINFRAME.updateMainframePane(MAINVOC,SET);
			SET.setAutosave(oldAutosave);
			MAINVOC.saveVocabularyIfAutosave(MAINVOC.getVocabulary(vocName));
			amwFrame.setVisible(true);
			CustomScrollPane addsJsp = new CustomScrollPane(adds);
			addsJsp.setPreferredSize(new Dimension(300,200));
			if(wta.size()>0){
				JOptionPane.showMessageDialog(amwFrame, addsJsp);
			}
			amwFrame.packAndKeepBounds();
		}
	}
}